import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Dependencies,
} from "@nestjs/common";
import { FastifyRequest } from "fastify";
import { Observable, of } from "rxjs";
import { tap } from "rxjs/operators";
import { PrismaClient } from "@prisma/client";
import { UserTokenService } from "../token.service";
import { WebResult } from "src/common/web.result";

@Injectable()
@Dependencies(PrismaClient, UserTokenService)
export class LoginInterceptor implements NestInterceptor {
  constructor(
    private readonly prisma: PrismaClient,
    private readonly userTokenService: UserTokenService
  ) {}

  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<any> | Promise<Observable<any>> {
    return new Promise(async (resolve) => {
      const now = Date.now();

      const request: FastifyRequest = context.switchToHttp().getRequest();
      // const token = this.userTokenService.getTokenFromRequest(request);

      // if (!token) {
      //   resolve(of(WebResult.failure(undefined, "请先登录")));
      //   return;
      // }

      // console.log("验证用户token", token);
      // const userData = this.userTokenService.getUserDataFromToken(token);
      // if (!userData || !userData.id || !userData.username) {
      //   resolve(of(WebResult.failure(undefined, "token is wrong")));
      //   return;
      // }

      // const user = await this.prisma.user.findUnique({
      //   select: {
      //     id: true,
      //     password: true,
      //   },
      //   where: {
      //     id: userData.id,
      //     username: userData.username,
      //   },
      // });
      // if (!user) resolve(of(WebResult.failure(undefined, "不存在的用户")));

      // try {
      //   await this.userTokenService.verifyToken(token, user.password)
      //   resolve(
      //     next
      //       .handle()
      //       .pipe(tap(() => console.log(`After... ${Date.now() - now}ms`))),
      //   );
      // } catch (e) {
      //   console.error(e);
      //   resolve(of(WebResult.failure(undefined, "权限不足")));
      // }

      const loginInfo = await this.userTokenService.isLogin(request);
      if (loginInfo.status === "no token") {
        resolve(of(WebResult.failure(undefined, "请先登录")));
      } else if (loginInfo.status === "wrong token") {
        resolve(of(WebResult.failure(undefined, "token is wrong")));
      } else if (loginInfo.status === "not exists user") {
        resolve(of(WebResult.failure(undefined, "用户不存在")));
      } else if (loginInfo.status === "verify error") {
        resolve(of(WebResult.failure(undefined, "权限不足")));
      } else if (loginInfo.status === "login") {
        resolve(
          next
            .handle()
            .pipe(tap(() => console.log(`After... ${Date.now() - now}ms`))),
        );
      } else {
        resolve(of(WebResult.failure(undefined, "请先登录")));
      }
    });
  }
}
